import 'dart:convert';

import 'package:flutter/widgets.dart';
import 'package:lib_core/lib_core.dart';
import 'package:lib_furnace/api/furnace_host_api_v2.dart';
import 'package:lib_furnace/lib_furnace.dart';

/// Author: Shper
/// Created: 2023-08-10
class GTNavigatorObserver extends NavigatorObserver {

  final GTFurnaceHostApiV2 _hostApiV2 = GTFurnaceHostApiV2();

  @override
  void didPush(Route route, Route? previousRoute) {
    GTLogger.debug("$runtimeType - didPush");
    _addStartPageName(route.settings.name);
    _onRouteChange(route);
    super.didPush(route, previousRoute);
  }

  @override
  void didPop(Route route, Route? previousRoute) {
    GTLogger.debug("$runtimeType - didPop");
    _removeStartPage(route.settings.name);
    _onRouteChange(route);
    super.didPop(route, previousRoute);
  }

  @override
  void didReplace({Route? newRoute, Route? oldRoute}) {
    GTLogger.debug("$runtimeType - didReplace");
    _removeStartPage(oldRoute?.settings.name);
    _addStartPageName(newRoute?.settings.name);
    _onRouteChange(newRoute);
    super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
  }

  @override
  void didRemove(Route route, Route? previousRoute) {
    GTLogger.debug("$runtimeType - didRemove");
    _removeStartPage(route.settings.name);
    _onRouteChange(route);
    super.didRemove(route, previousRoute);
  }

  void _onRouteChange(Route? route) {
    /// 通知原生是否可以开启侧滑返回手势
    /// 当canPop()为 true 时说明导航处于二级或多级界面，此时原生需要禁止原生的侧滑返回
    /// 当canPop()为 false 时说明导航处于一级界面，此时原生需要打开原生的侧滑返回
    var message = <String, dynamic>{};
    message["flutterPageCanPop"] = route?.navigator?.canPop() ?? false;
    GTFurnace.navigationMessageChannel.send(json.encode(message));
  }

  void _addStartPageName(String? routeName) {
    if(null==routeName || routeName.isEmpty) return;
    _hostApiV2.addStartPageName(routeName);
    if(GTRouter.pageStartedList.contains(routeName)){
      GTRouter.pageStartedList.remove(routeName);
    }
    GTRouter.pageStartedList.add(routeName);
  }

  void _removeStartPage(String? routeName) {
    if(null==routeName || routeName.isEmpty) return;
    _hostApiV2.removeStartPage(routeName);
    GTRouter.pageStartedList.remove(routeName);
  }
}